#include "cal_bits.h"

void IntToByte(unsigned char* data, int value)
{
	*(int*)data = value;
}

int ByteToInt(unsigned char* data)
{
	return *(int*)data;
}

unsigned char GetBits(unsigned char in, int from, int to)
{
	unsigned char ret = 0;
	unsigned char CurBit = 1;
	for (int i=from ; i<=to ; i++)
	{
		if (((1<<i)&in)!=0)
			ret += CurBit;
		CurBit = CurBit<<1;
	}
	return ret;
}

int GetBits(int source, int from, int to)
{
	unsigned int ret = source;
	ret = ret<<(31-from);
	ret = ret>>(31-from+to);
	return ret;
}

int GetBits(unsigned __int64 source, int from, int to)
{
	unsigned __int64 ret = source;
	ret = ret<<(63-from);
	ret = ret>>(63-from+to);
	return ret;
}

void SetBits(int& dest, int from, int to, int val)
{
	unsigned int mask = ~0;
	mask = mask<<(31-from);
	mask = mask>>(31-from+to);
	mask = mask<<to;
	mask = ~mask;
	dest = (dest&mask) + (val<<to);
}

void SetBits(unsigned __int64& dest, int from, int to, int val)
{
	unsigned __int64 mask = ~0;
	mask = mask<<(63-from);
	mask = mask>>(63-from+to);
	mask = mask<<to;
	mask = ~mask;
	dest = (dest&mask) + (val<<to);
}

void SetBits(unsigned char& dest, int to,int from,  unsigned char val)
{
	int IntDest = dest;
	SetBits(IntDest, from, to, int(val));
	dest = (unsigned char)IntDest;
}

short GetInt16(unsigned char byte0, unsigned char byte1)
{
	short IntVal;
	unsigned char* uctmp = (unsigned char*)&IntVal;
	uctmp[0] = byte0;
	uctmp[1] = byte1;
	return IntVal;
}

int GetInt32(unsigned char byte0, unsigned char byte1, unsigned char byte2, unsigned char byte3)
{
	int tmp;
	unsigned char* uctmp = (unsigned char*)&tmp;
	uctmp[0] = byte0;
	uctmp[1] = byte1;
	uctmp[2] = byte2;
	uctmp[3] = byte3;
	return tmp;
}

void SetInt16(unsigned char& byte0, unsigned char& byte1, short value)
{
//BUG test this function
	char* data = (char*)&value;
	byte0 = data[0];
	byte1 = data[1];
}

void SetInt32(unsigned char& byte0, unsigned char& byte1, unsigned char& byte2, unsigned char& byte3, int value)
{
//BUG test this function
	char* data = (char*)&value;
	byte0 = data[0];
	byte1 = data[1];
	byte2 = data[2];
	byte3 = data[3];
}
